package com.teamclub.pay.sservices.third.weixin

import java.util.UUID

import io.ebean.Ebean
import com.fasterxml.jackson.databind.JsonNode
import com.google.common.collect.ImmutableMap
import com.teamclub.domain.pay.order.{PayInfoConf, PayOrder}
import com.teamclub.pay.confs.PayConf
import com.teamclub.pay.sforms.PayOrderForm
import com.teamclub.pay.sservices.third.IPayService
import com.teamclub.util.errors.ErrorCode
import com.teamclub.util.libs.{F, Json}
import org.apache.commons.lang3.StringUtils
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import weixin.popular.api.PayMchAPI
import weixin.popular.bean.paymch.{MchOrderquery, Unifiedorder}
import weixin.popular.util.PayUtil

@Service("weixin.payservice")
class WxPayService extends IPayService {
  val logger = LoggerFactory.getLogger(getClass)
  @Autowired
  var payConf: PayConf = _

  override def appPay(form: PayOrderForm):  F.Either[JsonNode, ErrorCode] = {
    //组装相关参数
    val payInfoConf = Ebean.find(classOf[PayInfoConf]).where().eq("organNo", form.getOrganNo).findOne()
    val unifiedorder = new Unifiedorder
    unifiedorder.setAppid(payInfoConf.getThirdAppId)
    unifiedorder.setMch_id(payInfoConf.getThirdMchId)
    unifiedorder.setNonce_str(UUID.randomUUID().toString().replace("-", ""))
    unifiedorder.setBody(form.getGoods)
    unifiedorder.setOut_trade_no(form.getOrderNum)
    unifiedorder.setTotal_fee(form.getTotalFee.toString)
    unifiedorder.setSpbill_create_ip(form.getCreateIp)
    unifiedorder.setNotify_url(payInfoConf.getThirdNotifyUrl)
    unifiedorder.setTrade_type(form.getTradeType)
    logger.info("unify order req: {}", Json.toJson(unifiedorder))
    val unifiedorderResp = PayMchAPI.payUnifiedorder(unifiedorder, payInfoConf.getThirdAppKey)
    logger.info("unify order resp: {}", Json.toJson(unifiedorderResp))
    if(unifiedorderResp.getSign_status != null && unifiedorderResp.getSign_status) {
      val payData = PayUtil.generateMchAppData(unifiedorderResp.getPrepay_id, payInfoConf.getThirdAppId, payInfoConf.getThirdMchId, payInfoConf.getThirdAppKey)
      return F.Either.Left(Json.toJson(ImmutableMap.of("payData", payData, "organNum", form.getOrderNum)))
    } else {
      return F.Either.Right(ErrorCode.ref(unifiedorderResp.getReturn_msg + unifiedorderResp.getErr_code_des))
    }
  }

  override def thirdQuery(form: PayOrderForm, order: PayOrder): F.Either[PayOrder, ErrorCode] = {
    val payInfoConf = Ebean.find(classOf[PayInfoConf]).where().eq("organNo", form.getOrganNo).findOne()
    val where = Ebean.find(classOf[PayOrder]).where()
    val mchOrderquery = new MchOrderquery
    mchOrderquery.setAppid(payInfoConf.getThirdAppId)
    mchOrderquery.setMch_id(payInfoConf.getThirdMchId)
    mchOrderquery.setNonce_str(UUID.randomUUID().toString().toString().replace("-", ""))
    mchOrderquery.setOut_trade_no(order.getOrderNum)
    logger.info("order query req: {}", Json.toJson(mchOrderquery))
    val orderqueryResp = PayMchAPI.payOrderquery(mchOrderquery, payInfoConf.getThirdAppKey)
    logger.info("order query resp: {}", Json.toJson(orderqueryResp))
    if(orderqueryResp.getSign_status != null && orderqueryResp.getSign_status) {
      if("SUCCESS" == orderqueryResp.getReturn_code) {
        if("SUCCESS" == orderqueryResp.getResult_code) {
          order.setThirdOrderNum(orderqueryResp.getTransaction_id)
          order.setPayResult(1)
          order.setPayResultMsg("支付成功")
          order.update()
        }
      } else {
        return F.Either.Right(ErrorCode.ref(orderqueryResp.getReturn_msg))
      }
    }
    return F.Either.Left(order)
  }
}
